package com.tmt.sm.impl;

import com.tmt.sm.ISmSender;
import com.tmt.sm.ISmSenderProxy;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

public class DefaultSmSenderProxy implements ISmSenderProxy {

    private List<ISmSender> smSenderList = new ArrayList<>();

    @Override
    public void addSender(ISmSender smSender) {
        smSenderList.add(smSender);
    }

    @Override
    public boolean support(ReturnMode returnMode) {
        return smSenderList.stream().anyMatch(x->x.support(returnMode));
    }

    @Override
    public SendResult send(String toMobile, String content, Date sendTime, ReturnMode returnMode) {
        if (smSenderList.size() <= 0)
            return new SendResult(null, -999,"未配置短信发送器对象", false);

        List<ISmSender> validSenderList = smSenderList.stream()
                .filter(x->x.support(returnMode)).collect(Collectors.toList());
        if (validSenderList.size() <= 0)
            return new SendResult(null, -998,"未找到合适的短信发送器对象", false);

        //随机选择一个发送者进行发送
        int d = (int)(1000 * Math.random());
        int index = d % validSenderList.size();
        return validSenderList.get(index).send(toMobile, content, sendTime, returnMode);
    }

}
